/*
 * =====================================================================================
 *
 *       Filename:  tds.h
 *
 *    Description:  freetdh 封装
 *
 *        Version:  1.0
 *        Created:  09/18/2017 10:39:32 AM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */

#ifndef TDS_INCLUDE_H
#define TDS_INCLUDE_H

#include <string>
#include <vector>
#include <map>
#include "sybfront.h"
#include "sybdb.h"

using std::string;
using std::map;
using std::vector;

struct TdsDbConfig
{
    string      server;
    string      dbname;
    string      user;
    string      passwd;
    unsigned int    logintimeout;
    unsigned int    rwtimeout;
};

// mssql 服务停止后，如果没有注册错误处理函数，会导致进程退出
int typedef (*tds_msg_handler)(DBPROCESS *dbproc, DBINT msgno, int msgstate, int severity,
        char *msgtext, char *srvname, char *procname, int line);

int typedef (*tds_err_handler)(DBPROCESS * dbproc, int severity, int dberr, int oserr,
        char *dberrstr, char *oserrstr);

class CTds
{
public:
    CTds();
    ~CTds();
    
    bool Init(const string& server,const string& dbname,const string& user,const string& passwd,
            unsigned int loginTimeout,unsigned int rwTimeout,
            tds_msg_handler mh = NULL,tds_err_handler eh = NULL);

    // 内部的vector表示一行的字段值，值的顺序为DbBind的顺序，即实际返回的顺序
    // map表多示多个结果集，比如两个select，各返回4条记录
    // map从0开始，0表示第一个select的记录
    void Execute(const string& cmd,map<int,vector< vector<string> > >& results);

    // 同上，只是引用返回的数据的方式不同
    void Execute(const string& cmd,map<int,vector< map<string,string> > >& results);

private:
    bool DbConnect();
    bool IsConnected();
    TdsDbConfig   m_dbCfg;
    DBPROCESS     *m_proc;
    tds_msg_handler  m_mh;
    tds_err_handler  m_eh;
};


#endif












